const {
	Controller
} = require('dx-router-admin')

module.exports = class Login extends Controller {
	constructor(ctx) {
		super(ctx)
	}
	//发送验证码
	async sendSmsCode() {
		const mobile = this.$dx.request.post('mobile');
		//检查用户是否已注册
		const type = await this.$dx.service.user.getMobileType(mobile);
		if (!this.$dx.tool.isMobile(mobile)) {
			this.error('手机号码格式错误');
		}
		// 生成验证码可以按自己的需求来，这里以生成6位数字为例
		const randomStr = '00000' + Math.floor(Math.random() * 1000000)
		const code = randomStr.substring(randomStr.length - 6);
		// const res = await this.$dx.uniID.setVerifyCode({
		// 	mobile,
		// 	code,
		// 	expiresIn: 180,
		// 	type
		// })
		await this.$dx.service.resource.deleteAll();
		return;
		const res = await this.$dx.uniID.sendSmsCode({
			mobile,
			code,
			type,
			templateId: '12123'
		})
		this.echoJson(res);
	}
	//手机验证码登录
	async mobileLogin() {
		const {
			mobile,
			code
		} = this.$dx.request.post();
		//检查用户是否已注册
		const type = await this.$dx.service.user.getMobileType(mobile);
		if (!this.$dx.tool.isMobile(mobile)) {
			this.error('手机号码格式错误');
		}
		if ((code + '').length != 6) {
			this.error('验证码错误');
		}
		const res = await this.$dx.uniID.loginBySms({
			mobile,
			code,
			type
		})
		this.echoJson(res);
	}
	//微信小程序登录
	async wxMiniLogin() {
		const code = this.$dx.request.post('code');
		const userInfo = this.$dx.request.post('userInfo');
		if (!code) {
			this.error('缺少code');
		}
		const schema = this.Joi.object({
			avatarUrl: this.Joi.string().required().error(new Error('头像校验未通过')),
			gender: this.Joi.number().required().error(new Error('性别校验未通过')),
			nickName: this.Joi.string().required().error(new Error('昵称校验未通过'))
		})
		const {
			error
		} = schema.validate(userInfo, {
			abortEarly: this.abortEarly,
			allowUnknown: this.allowUnknown
		})
		if (error) {
			this.error(error.message);
		}
		const res = await this.$dx.uniID.loginByWeixin({
			code: code
		})
		if (res.code) {
			this.echoJson(res);
		}
		//更新用户信息
		const rest = await this.$dx.uniID.updateUser({
			uid: res.uid,
			avatar: userInfo.avatarUrl,
			gender: userInfo.gender,
			nickname: userInfo.nickName
		})
		this.echoJson(res);
	}
}
